<template>
  <div>
    <template v-if="isOpenData">
      <div>
        <publink-select
          class="user-search"
          :value="_value"
          @change="changeHanlder"
          :ref="'user_' + field.fieldName"
          filterable
          remote
          :placeholder="field.placeHolder ? field.placeHolder : $t('common.base.inputKeywordToSearch')"
          :clearable="field.noClearable ? false : true"
          :loading="loading"
          :multiple="multiple"
          :remote-method="searchUser"
          :popper-append-to-body="false"
          v-el-select-loadmore={loadmoreOptions}
          is-search-user
        >
          <el-option
            v-for="(item, index) in options"
            :key="`${item.id}_${index}`"
            :label="item.name || label"
            :origin="item"
            :value="field.returnData ? item[field.returnData] : item.id"
          >
            <template v-if="isOpenData">
              <open-data type="userName" :openid="item.staffId || item.name || item.label"></open-data>
              <template v-if="item.isDelete == 1">{{ ` (${t('common.base.resigned')})` }}</template>
            </template>
          </el-option>
          
          <!-- <template slot="multiple" slot-scope="{ item }">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="item.staffId || item.name || item.label"></open-data>
            </template>
            <template v-else>
              {{item.name}}
            </template>
          </template> -->
          
        </publink-select>
      </div>
    </template>
    <template v-else>
      <publink-select
        class="user-search"
        :value="_value"
        @input="choose"
        :ref="'user_'+field.fieldName"
        filterable
        remote
        :placeholder="field.placeHolder ? field.placeHolder : $t('common.base.inputKeywordToSearch')"
        :clearable="field.noClearable ? false : true"
        :loading="loading"
        :multiple="multiple"
        :remote-method="searchUser"
        :popper-append-to-body="false"
        v-el-select-loadmore={loadmoreOptions}
      >
        <el-option
          v-for="(item, index) in options"
          :key="`${item.id}_${index}`"
          :label="item.name"
          :origin="item"
          :value="field.returnData ? item[field.returnData] : item.id"
        >
          
          <template v-if="isOpenData">
            <open-data type="userName" :openid="item.staffId"></open-data>
          </template>
          
        </el-option>
        
        <template slot="multiple" slot-scope="{ item }">
          <template v-if="isOpenData">
            <open-data type="userName" :openid="item.staffId"></open-data>
          </template>
          <template v-else>
            {{item.name}}
          </template>
        </template>
        
      </publink-select>
    </template>
  </div>

</template>

<script>
/* api */
import { getUserTag } from '@src/api/CustomerApi.ts'
/* mixin */
import FormMixin from '@src/component/form/mixin/form'
/* model */
import Page from '@model/Page'
/* util */
import Log from '@src/util/log.ts'
import { debounce } from '@src/util/function'
import { isArray } from '@src/util/type'
import { isOpenData } from '@src/util/platform'
import { t } from '@src/locales'
export default {
  name: 'user-search',
  mixins: [FormMixin],
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String | Array,
      default: '',
    },
    userList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    _value() {
      const multiple = this.multiple
      let value = this.value
      
      if (multiple && !isArray(value)) {
        value = value ? [value] : []
      }
      else if(!multiple && isArray(value)) {
        value = value?.[0]
      }
      return value
    },
  },
  watch: {
    /* 判断是否自定义视图进来的 */
    /* 客户高级搜索协同人也使用了该字段 */
    userList(v) {
      if (Array.isArray(v) && v.length) {
        this.options = v;
      }
    },
  },
  data() {
    return {
      isOpenData,
      isOpenDataSelect: false,
      staffIds: [],
      loading: false,
      options: [],
      loadmoreOptions: {
        disabled: false,
        callback: this.loadmore,
        distance: 10,
      },
      page: new Page()
    };
  },
  created() {
    let options = sessionStorage.getItem(`${this.field.fieldName}_options`);
    if (Array.isArray(this.userList) && this.userList.length) {
      this.options = this.userList;
    } else {
      if(!this.isOpenData) {
        this.options = JSON.parse(options || '[]');
      }
    }
    if(!this.options.length){
      this.searchUser('');
    }
  },
  methods: {
    selectOpenDataHandler(){
      this.isOpenDataSelect = true
      this.$nextTick(()=>{
        const parentEl = this.$refs[`user_${this.field.fieldName}`];
        parentEl.focus()
      })
    },
    changeHanlder(e){
      this.isOpenDataSelect = false
      this.choose(e)
    },
    choose(newValue) {
      let oldValue = null;
      
      // 清空搜索输入的值
      const parentEl = this.$refs[`user_${this.field.fieldName}`];
      const publinkEl = parentEl?.$refs?.PublinkElement;
      const elementEl = this.isOpenData ? publinkEl : parentEl;
      if (elementEl) elementEl.query = '';
      
      // if(this.isOpenData && newValue) {
      //   let value = newValue
      //   const multiple = this.multiple
      //   if (multiple && !isArray(value)) {
      //     value = value ? [value] : []
      //   } else if(!multiple && isArray(value)) {
      //     value = value?.[0]
      //   } else if(!multiple && !isArray(value)) {
      //     value = value ? [value] : []
      //   } 
      //   // console.log('value', value);
      //   if(value && value.length && this.options.length) {
      //     for (let index = 0; index < value.length; index++) {
      //       const option = this.options.find(item=>item.id == value[index] || item.staffId == value[index])
      //       this.staffIds = []
      //       if(option && option.staffId) this.staffIds.push(option.staffId)
      //     }
      //   } 
      // }
      
      this.$emit('update', { newValue, oldValue, field: this.field, options: this.options });
    },
    async fetchRemoteData(keyword) {
      // 参数
      const params = { keyword, pageNum: this.page.pageNum }

      try {
        const result = await getUserTag(params)
        this.loadmoreOptions.disabled = Boolean(!result?.hasNextPage)
        return result
      } catch (error) {
        Log.error(error, this.fetchRemoteData.name)
        return {}
      } finally {
        this.loading = false
      }

    },
    async loadmore() {
      if (this.loading || this.loadmoreOptions.disabled) return

      this.loadmoreOptions.disabled = true
      this.loading = true
      this.page.pageNum += 1

      try {
        const result = await this.fetchRemoteData()
        const userList = result?.list

        this.page.merge(result)
        this.setOptions(userList)

      } catch (error) {
        Log.error(error, this.loadmore.name)
      }

    },
    setOptions(users = []) {
      const options = users.slice()

      this.options = this.options.concat(
        options.map(({ displayName, userId, staffId, isDelete }) => {
          return (
            Object.freeze({
              name: displayName + (isDelete == 1 ? ` (${t('common.base.resigned')})` : ''),
              id: userId,
              staffId,
              isDelete
            })
          )
        })
      )

      this.setSessionStorageOptions()
    },
    setSessionStorageOptions() {
      sessionStorage.setItem(
        `${this.field.fieldName}_options`,
        JSON.stringify(this.options)
      )
    },
    searchUser(keyword) {
      debounce(async () => {
        if (this.loading) return

        this.loading = true
        this.page = new Page()
        this.options = []
        this.$emit('input', { keyword, field: this.field })

        try {
          const result = await this.fetchRemoteData(keyword)
          const userList = result?.list

          this.page.merge(result)
          this.setOptions(userList)
          
          const selectComponent = this.$refs[`user_${this.field.fieldName}`];
          this.$nextTick(() => {
            selectComponent.setIsHaveValue && selectComponent.setIsHaveValue()
          })
          
        } catch (error) {
          Log.error(error, this.loadmore.name)
        }
      })
    }
  }
};
</script>

<style lang="scss">
.user-search {
  width: 100%;
  .el-tag .open-data{
    margin-right: 0;
  }
}
</style>
